package com.zhitong.money.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhitong.money.entity.Role;
import com.zhitong.money.exception.AddException;
import com.zhitong.money.exception.DeleteException;
import com.zhitong.money.exception.RepeatException;
import com.zhitong.money.exception.UpdateException;
import com.zhitong.money.mapper.RoleMapper;
import com.zhitong.money.mapper.RoleMenuMapper;
import com.zhitong.money.mapper.RolePerMapper;
import com.zhitong.money.mapper.UserRolemapper;
import com.zhitong.money.services.api.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class RoleService implements IRoleService {

    @Autowired
    private RoleMapper mapper;

    @Autowired
    private RolePerMapper rolePerMapper;

    @Autowired
    private UserRolemapper userRolemapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public Role findRoleById(String id) throws Exception {
        Role roleById = mapper.findRoleById(id);
        if (roleById==null){
            throw new NullPointerException("findRoleById:查询为空");
        }
        return roleById;
    }

    @Override
    public List<String> findPidsById(String id) throws Exception {
        List<String> pidsByRid = rolePerMapper.findPidsByRid(id);
        return pidsByRid;
    }

    @Override
    public List<Role> findAllRole() throws Exception {
            List<Role> allRole = mapper.findAllRole();
            if (allRole==null || allRole.isEmpty()){
                throw new NullPointerException("findAllRole:查询为空");
            }
            return allRole;
    }

    @Override
    public PageInfo findRoleByPage(Map<String,Object> map) throws Exception {
        int pageNum=map.containsKey("pageNum")?(int)map.get("pageNum"):1;
        int pageSize=map.containsKey("pageSize")?(int)map.get("pageSize"):5;
        PageHelper.startPage(pageNum,pageSize);
        List<Role> roleByMap = mapper.findRoleByMap(map);
        if (roleByMap==null || roleByMap.isEmpty()){
            throw new NullPointerException("findRoleByPage:查询角色为空");
        }
        return new PageInfo(roleByMap);

    }

    @Override
    public List<Role> findRoleByMap(Map<String, Object> map) throws Exception {
        List<Role> roleByMap = mapper.findRoleByMap(map);
        if (roleByMap==null || roleByMap.isEmpty()){
            throw new NullPointerException("findRoleByPage:查询角色为空");
        }
        return roleByMap;
    }

    @Transactional
    @Override
    public void addRole(Map<String, Object> map) throws Exception{
        Role roleByName = mapper.findRoleByName(map.get("name").toString().trim());
        if (roleByName!= null){
            throw new RepeatException("角色已存在!");
        }
        Role role=new Role();
        role.setName(map.get("name").toString());
        role.setDescription(map.get("description").toString());
        role.setStatus(map.get("status").toString());
        try {
            //判断该角色是否选择了权限
            List<String> permissionIds=(List<String>) map.get("permissions");
            if (permissionIds!=null){
                for (String pid:permissionIds){
                    rolePerMapper.add(role.getId(),pid);
                }
            }
            //添加菜单资源
            List<String> menus = (List<String>) map.get("menus");
            if (menus!=null && !  menus.isEmpty()){
                for (String mid:menus){
                    roleMenuMapper.add(role.getId(),mid);
                }
            }
            mapper.addRole(role);
        } catch (Exception e) {
            log.error("添加角色失败:"+e.getMessage());
            throw new AddException();
        }
    }


    @Transactional
    @Override
    public void updateRole(Map<String,Object> map) throws Exception{
        String id=map.get("id").toString();
        Role roleByName = mapper.findRoleByName(map.get("name").toString().trim());
        if (roleByName!= null && !id.equals(roleByName.getId())){
            throw new RepeatException("角色已存在");
        }
        try {
            //将原来所属权限删除,然后添加新的权限
            rolePerMapper.deleteByRid(id);
            List<String> permissions = (List<String>) map.get("permissions");
            if (permissions!=null && !  permissions.isEmpty()){
                for (String pid:permissions){
                    rolePerMapper.add(id,pid);
                }
            }
            //添加菜单资源
            roleMenuMapper.delByRid(id);
            List<String> menus = (List<String>) map.get("menus");
            if (menus!=null && !  menus.isEmpty()){
                for (String mid:menus){
                    roleMenuMapper.add(id,mid);
                }
            }

            //修改角色
            mapper.updateRole(map);
        } catch (Exception e) {
            log.error("更新角色失败:"+e.getMessage());
            throw new UpdateException();
        }

    }

    @Transactional
    @Override
    public int delRole(String id) throws Exception{
        try {
            //check
            int i = userRolemapper.countByRid(id);
            if (i==0){
                //删除角色与权限的关系
                rolePerMapper.deleteByRid(id);
                //删除角色与菜单的关系
                roleMenuMapper.delByRid(id);
                int i1 = mapper.delRole(id);
                return i1;
            }
            return -1;

        } catch (Exception e) {
            log.error("删除角色失败!");
            throw new DeleteException();
        }
    }

    @Transactional
    @Override
    public int delRolesByIds(List<String> ids) throws Exception {
        try {
            //check
            int i = userRolemapper.countByRids(ids);
            if (i==0){
                //删除角色与权限的关系
                rolePerMapper.deleteByRids(ids);
                //删除角色与菜单的关系
                roleMenuMapper.delByRids(ids);
                int i1 =  mapper.delRolesByIds(ids);
                return i1;
            }
            return -1;
        } catch (Exception e) {
            throw new DeleteException("delRolesByIds:删除失败");
        }
    }


}
